package com.cwd.arm.inter.conf.resolver;

import com.alibaba.fastjson.JSONObject;
import com.cwd.arm.inter.conf.annotation.ArmAliJsonRequestBody;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by yan on 21-12-25.
 */
public class ArmAliJsonResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(ArmAliJsonRequestBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  @Nullable ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {

        Class paramObjClass = methodParameter.getParameterType();
        String json = getRequestBody(nativeWebRequest);
        Object paramObj = paramObjClass.newInstance();
        Object object = JSONObject.parseObject(json, paramObjClass);
        return object != null ? object : paramObj;
    }

    private String getRequestBody(NativeWebRequest webRequest) {
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String jsonBody =null;
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        return jsonBody;
    }
}
